import re

from django import http
from django.contrib.auth import login
from django.shortcuts import render,redirect
from QQLoginTool.QQtool import OAuthQQ
from django.urls import reverse
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser, OAuthSinaUser
from apps.users.models import User
from meiduo_mail import settings

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from apps.oauth.utils import generic_openid_token,check_openid_token
# Create your views here.
from django.views import View
from libs import sinaweibopy3
from utils.response_code import RETCODE


class OauthQQLoginURLView(View):
    def get(self,requset):
        state = 'test'

        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=state
        )
        login_url = qq.get_qq_url()
        return http.JsonResponse({'login_url':login_url})



        # return http.JsonResponse({'login_url':'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101518219&redirect_uri=http://www.meiduo.site:8000/oauth_callback&state=test'})

class OauthQQUserView(View):
    def get(self,request):
        code = request.GET.get('code')
        state = request.GET.get('state')
        if code is None:
            return http.HttpResponseBadRequest('参数有误')
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=state
        )
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            token = generic_openid_token(openid)
            return render(request, 'oauth_callback.html', context={'openid':token})
        else:
            login(request, qquser.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username',qquser.user.username)
            return response
    def post(self,request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        openid = request.POST.get('openid')
        if not all([mobile,password,sms_code]):
            return http.HttpResponseBadRequest('参数不全')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('请输入正确的手机号码')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseBadRequest('请输入8-20位的密码')
        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的短信验证码'})
        if sms_code != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})
        openid=check_openid_token(openid)
        if openid is None:
            return http.HttpResponseBadRequest('数据被篡改')
        try:
            user = User.objects.get(mobile=mobile)
        except:
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile,
            )
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('绑定失败')
        print(user)

        OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username)
        return response




class OauthWBLoginURLView(View):
    def get(self,request):
        next_url = request.GET.get('next')
        client = sinaweibopy3.APIClient(
            app_key=settings.APP_KEY,
            app_secret=settings.APP_SECRET,
            redirect_uri=settings.REDIRECT_URL
        )
        login_url = client.get_authorize_url()
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': "OK",
            'login_url':login_url
        })



class WeiboCallBackView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return http.HttpResponseBadRequest('参数不全')
        client = sinaweibopy3.APIClient(
            app_key=settings.APP_KEY,
            app_secret=settings.APP_SECRET,
            redirect_uri=settings.REDIRECT_URL
        )
        result = client.request_access_token(code)
        access_token = result.access_token
        uid = result.uid
        try:
            weibouser = OAuthSinaUser.objects.get(uid=uid)
        except OAuthSinaUser.DoesNotExist:
            return render(request, 'oauth_callback.html', context={'openid': uid})
        else:
            user = weibouser.user
            login(request, user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', user.username)
            return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        uid = request.POST.get('openid')
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('绑定失败')
            OAuthSinaUser.objects.create(user=user, uid=uid)
            login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username)
        return response


